package com.hbnu.controller;

import com.hbnu.pojo.User;
import com.hbnu.service.UserService;
import com.hbnu.service.impl.UserServiceImpl;
import com.hbnu.util.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录
 *    请求地址：http://localhost:8080/login
 *    请求方式：POST
 *    请求参数：stuCode:0001  password:123456
 *
 * @author chendikai
 * @date 2024-10-30 下午 3:45
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");  // 为了防止中文乱码

        // 1、获取用户输入的学号和密码
        String stuCode = req.getParameter("stuCode");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");

        // 2、将用户输入的学号和密码进行数据库校验
        User user = userService.findUserByStuCodeAndPassword(stuCode, password);

        // 3、根据校验结果跳转到不同的页面
        if (user == null) {
            // 给前端返回一个错误提示信息
            req.setAttribute("error", "您输入的账号或密码有误...");

            // 跳转到用户登录页面
            req.getRequestDispatcher("index.jsp").forward(req, resp);   // 页面跳转
        } else {

            // 将用户数据存入session域（session会话）
            req.getSession().setAttribute("session_user", user);

            // 如果用户勾选了“记住我”，则将用户登录信息存入cookie中
            if ("remember-me".equals(remember)) {
                CookieUtils.addCookie("cookie_stu_pass", 7 * 24 * 3600, req, resp, stuCode, password);
            }

            // 跳转到系统主页面
            req.getRequestDispatcher("/jsp/main.jsp").forward(req, resp);
        }
    }
}
